package com.czyxy;

import com.csvreader.CsvWriter;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by mike on 6/8/17.
 */
@Service
public class CsvService {
    public String writeCsv(List<? extends CsvWritable> datalist,String path) throws Exception {
        if(datalist.size()<1){
            throw new Exception("数据条数至少为1");
        }
        String csvFilePath=path;
        try{
            CsvWriter w = new CsvWriter(csvFilePath,',', Charset.forName("UTF-8"));
            String[] headers={"姓名","年龄","性别"};
            w.writeRecord(datalist.get(0).ColumnHeaders());
            datalist.forEach(data->{
                try {
                    w.writeRecord(data.toStringArray());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            w.close();
            return csvFilePath;
        }catch (IOException e){
            e.printStackTrace();
            return "";
        }
    }

    public String writeCsv(List<? extends CsvWritable> datalist) throws Exception {
        return writeCsv(datalist,"datalist.csv");
    }
}
